//
//  TTFiltrateView.m
//  TaoTuo
//
//  Created by admin on 2019/8/20.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTFiltrateView.h"
#import "TTSearchTagViewCell.h"
#import "TTSearchInsertModel.h"

static NSString *cellIdentifier = @"ll_search_tag_id";

@interface TTFiltrateView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
{
    CGSize _itemSize;
}

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *selectedArray;    // 存放选中的item
@property (nonatomic, copy) SelectedItemArrayBlock selectedArrayBlock;
@property (nonatomic, copy) SelectedItemArrayAndViewBlock selectedItemArrayAndViewBlock;
@property (nonatomic, assign) BOOL allowsMultiple;      // 是否可以多选

@property (nonatomic, assign) BOOL isCharacter;     // 包含的是否是字符串
@property (nonatomic, assign) BOOL defaultSelectedFirst;    // 是否默认选中第一个

@property (nonatomic, assign) CGFloat leftRightSpace;       // 左右内边距
@property (nonatomic, assign) CGFloat cornerRadius;     // 圆角
@property (nonatomic, assign) BOOL allowsMultipleButAtLeastOne; // 允许多选，但至少要选中一个

///上次点击的indexPath
@property (nonatomic, strong) NSIndexPath *lastIndexPath;

@end

@implementation TTFiltrateView

- (instancetype)initWithFrame:(CGRect)frame allowsMultiple:(BOOL)allowsMultiple selectedItemArrayAndViewBlock:(SelectedItemArrayAndViewBlock)selectedArrayBlock
{
    self = [super initWithFrame:frame];
    if (self) {
        self.canCancelSelect = YES;
        self.allowsMultiple = allowsMultiple;
        self.selectedItemArrayAndViewBlock = selectedArrayBlock;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame allowsMultiple:(BOOL)allowsMultiple selectedArrayBlock:(SelectedItemArrayBlock)selectedArrayBlock leftRightSpace:(CGFloat)leftRightSpace
{
    return [self initWithFrame:frame allowsMultiple:allowsMultiple selectedArrayBlock:selectedArrayBlock leftRightSpace:leftRightSpace cornerRadius:0];
}

- (instancetype)initWithFrame:(CGRect)frame allowsMultipleButAtLeastOne:(BOOL)allowsMultipleButAtLeastOne selectedArrayBlock:(nonnull SelectedItemArrayBlock)selectedArrayBlock leftRightSpace:(CGFloat)leftRightSpace
{
    TTFiltrateView *view = [self initWithFrame:frame allowsMultiple:YES selectedArrayBlock:selectedArrayBlock leftRightSpace:leftRightSpace cornerRadius:0];
    view.allowsMultipleButAtLeastOne = allowsMultipleButAtLeastOne;
    return view;
}

- (instancetype)initWithFrame:(CGRect)frame allowsMultiple:(BOOL)allowsMultiple  selectedArrayBlock:(SelectedItemArrayBlock)selectedArrayBlock leftRightSpace:(CGFloat)leftRightSpace cornerRadius:(CGFloat)cornerRadius
{
    self = [super initWithFrame:frame];
    if (self) {
        self.canCancelSelect = YES;
        self.allowsMultiple = allowsMultiple;
        self.selectedArrayBlock = selectedArrayBlock;
        self.leftRightSpace = leftRightSpace;
        self.cornerRadius = cornerRadius;
    }
    return self;
}

- (void)setDataArray:(NSArray *)dataArray
{
    _dataArray = dataArray;
    
    self.isCharacter = [_dataArray.firstObject isKindOfClass:[NSString class]];
    
    [self.collectionView reloadData];
}

- (void)resetView
{
    [self.selectedArray removeAllObjects];
    [self.collectionView reloadData];
    
    if (self.selectedArrayBlock) {
        self.selectedArrayBlock(self.selectedArray);
    }
    
}

// 选中第一个不回调
- (void)setSelectedFirstItemAndNoBlock
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
}

// 选中第一个
- (void)setSelectedFirstItem
{
    self.defaultSelectedFirst = YES;
    self.canCancelSelect = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
        if (self.dataArray.count > 0) {
            if (!self.isCharacter) {
                TTSearchInsertModel *model = self.dataArray[indexPath.row];
                if (![self.selectedArray containsObject:model]) {
                    [self.selectedArray addObject:model];
                }
            } else {
                NSString *title = self.dataArray[indexPath.row];
                if (![self.selectedArray containsObject:title]) {
                    [self.selectedArray addObject:title];
                }
            }
        }
        
        if (self.selectedArrayBlock) {
            self.selectedArrayBlock(self.selectedArray);
        }
        
        if (self.selectedItemArrayAndViewBlock) {
            self.selectedItemArrayAndViewBlock(self, self.selectedArray, 0);
        }
        
    });
    
}

/// 设置选中某一个
- (void)setSelectedItemWithIndex:(NSInteger)index
{
    if (index >= self.dataArray.count) {
        return;
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    if (!self.isCharacter) {
        TTSearchInsertModel *model = self.dataArray[indexPath.row];
        if (![self.selectedArray containsObject:model]) {
            [self.selectedArray addObject:model];
        }
    } else {
        NSString *title = self.dataArray[indexPath.row];
        if (![self.selectedArray containsObject:title]) {
            [self.selectedArray addObject:title];
        }
    }
    
    if (self.selectedArrayBlock) {
        self.selectedArrayBlock(self.selectedArray);
    }
    if (self.selectedItemArrayAndViewBlock) {
        self.selectedItemArrayAndViewBlock(self, self.selectedArray, 0);
    }
}

///滚动到第几个item
- (void)scrollToIndex:(NSInteger)index
{
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

/// 让某个item居中
- (void)scrollToCenterWithIndex:(NSInteger)index
{
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

///设置偏移量
- (void)scrollToOffsetX:(CGFloat)offsetX
{
    [self.collectionView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

///默认选中前index个
- (void)defaultSelectBeforeIndex:(NSInteger)index
{
    for (int i = 0; i <= index; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
        if (self.isCharacter && ![self.selectedArray containsObject:self.dataArray[i]]) {
            [self.selectedArray addObject:self.dataArray[i]];
        }
        if (!self.isCharacter && ![self.selectedArray containsObject:self.dataArray[i]]) {
            TTSearchInsertModel *model = self.dataArray[indexPath.row];
            [self.selectedArray addObject:model];
        }
    }
    
    if (self.selectedArrayBlock) {
        self.selectedArrayBlock(self.selectedArray);
    }
}

// 选中前几个(index及其之前的)
- (void)selectWithIndex:(NSInteger)index
{
    // 刷新前三个
    NSMutableArray *indexPaths = [NSMutableArray array];
    for (int i = 0; i < 3; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [indexPaths addObject:indexPath];
    }
    [self.collectionView reloadItemsAtIndexPaths:indexPaths];
    // 取出数组中的前三个元素
    NSMutableArray *array3 = [NSMutableArray array];
    for (int i = 0; i < 3; i++) {
        [array3 addObject:self.dataArray[i]];
    }
    // 取出 self.selectedArray 中不在前三个元素中的其他元素，等会在放入 self.selectedArray 中
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(SELF in %@)", array3];
    NSArray *result = [self.selectedArray filteredArrayUsingPredicate:predicate];
    // 先清空元素
    [self.selectedArray removeAllObjects];
    // 把之前不在前三个元素的还添加进去
    [self.selectedArray addObjectsFromArray:result];
    
    for (int i = 0; i <= index; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        [self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
        if (self.isCharacter && ![self.selectedArray containsObject:self.dataArray[i]]) {
            [self.selectedArray addObject:self.dataArray[i]];
        }
    }
    
    if (self.selectedArrayBlock) {
        self.selectedArrayBlock(self.selectedArray);
    }
    
    if (self.selectedItemArrayAndViewBlock) {
        self.selectedItemArrayAndViewBlock(self, self.selectedArray, index);
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = @"";
    if (!self.isCharacter) {
        TTSearchInsertModel *model = self.dataArray[indexPath.row];
        title = model.title;
    } else {
        title = self.dataArray[indexPath.row];
    }
    TTSearchTagViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell setTitle:title cornerRadius:self.cornerRadius];
    if (self.normalBackgroundColor) {
        cell.normalBackgroundColor = self.normalBackgroundColor;
    }
    if (self.selectedBackgroundColor) {
        cell.selectedBackgroundColor = self.selectedBackgroundColor;
    }
    if (self.normalTitleColor) {
        cell.normalTitleColor = self.normalTitleColor;
    }
    if (self.selectedTitleColor) {
        cell.selectedTitleColor = self.selectedTitleColor;
    }
    if (self.boardColor) {
        cell.boardColor = self.boardColor;
    }
    if (self.boardWidth) {
        cell.boardWidth = self.boardWidth;
    }
    
    return cell;
}


- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.defaultSelectedFirst || !self.canCancelSelect) {
        return YES;
    }
    
    self.lastIndexPath = indexPath;
    
    TTSearchTagViewCell *cell = (TTSearchTagViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if (cell.selected) {
        // 单选取消选中
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        [self collectionView:collectionView didDeselectItemAtIndexPath:indexPath];
        return NO;
    }
    return YES;
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.lastIndexPath = indexPath;
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.isCharacter) {
        TTSearchInsertModel *model = self.dataArray[indexPath.row];
        if (![self.selectedArray containsObject:model]) {
            [self.selectedArray addObject:model];
        }
    } else {
        NSString *title = self.dataArray[indexPath.row];
        if (![self.selectedArray containsObject:title]) {
            [self.selectedArray addObject:title];
        }
    }
    
    
    if (self.selectedArray.count > 1 && !self.isCharacter) {
        [self.selectedArray sortUsingComparator:^NSComparisonResult(TTSearchInsertModel *  _Nonnull obj1, TTSearchInsertModel *  _Nonnull obj2) {
            // 按数字排序
            return [obj1.title compare:obj2.title options:NSNumericSearch];
        }];
    }
    
    
    if (self.selectedArrayBlock) {
        self.selectedArrayBlock(self.selectedArray);
    }
    
    if (self.selectedItemArrayAndViewBlock) {
        self.selectedItemArrayAndViewBlock(self, self.selectedArray, indexPath.row);
    }
    
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    id obj = self.dataArray[indexPath.row];
    
    // 至少选中一个
    if (self.selectedArray.count == 1 && self.allowsMultipleButAtLeastOne) {
        [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
        return;
    }
    
    [self.selectedArray removeObject:obj];
    
    if (indexPath == self.lastIndexPath) {
        if (self.selectedArrayBlock) {
            self.selectedArrayBlock(self.selectedArray);
        }
    }
    
}

- (void)setFixWidthAndHeight:(CGSize)itemSize
{
    _itemSize = itemSize;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_itemSize.width > 0) {
        return _itemSize;
    }
    NSString *titleStr = @"";
    if (!self.isCharacter) {
        TTSearchInsertModel *model = self.dataArray[indexPath.row];
        titleStr = model.title;
    } else {
        titleStr = self.dataArray[indexPath.row];
    }
    
    CGFloat space = self.leftRightSpace == 0 ? 18 : self.leftRightSpace * 2;
    CGFloat h = self.height - 10;
    CGFloat w = [titleStr boundingRectWithSize:CGSizeMake(MAXFLOAT, h) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} context:nil].size.width + space;
    w = w < 50 ? 50 : w;
    return CGSizeMake(w, h);
}

- (void)setLayoutConfigWithMinimumLineSpacing:(CGFloat)minimumLineSpacing minimumInteritemSpacing:(CGFloat)minimumInteritemSpacing sectionInset:(UIEdgeInsets)sectionInset
{
     UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    layout.minimumLineSpacing = minimumLineSpacing;
    layout.minimumInteritemSpacing = minimumInteritemSpacing;
    layout.sectionInset = sectionInset;
    
}



- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 5;
        layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.allowsMultipleSelection = self.allowsMultiple;  // 可多选
        [_collectionView registerClass:[TTSearchTagViewCell class] forCellWithReuseIdentifier:cellIdentifier];
        [self addSubview:_collectionView];
        
    }
    return _collectionView;
}

- (NSMutableArray *)selectedArray
{
    if (!_selectedArray) {
        _selectedArray = [NSMutableArray array];
    }
    return _selectedArray;
}

@end
